<?php
namespace Task\App\ZduScreen;

use Task\Core\RedisQueueService;
use Task\Core\RedisService;
use Task\Core\Base;
use JPush\Client;

class ZduScreen extends Base
{
    public $mysql;

    public function __construct()
    {
        parent::__construct();
        $this->mysql = $this->selectDB('mysql');
    }

    //删除上菜记录表
    public function delLog(){
        $table = 'restaurant_order_goods_log';
        $result = $this->mysql->delete($table,array('goods_status'=>2));
        echo $result;
    }

    //每天凌晨清除redis里面浙大小乐惠与浙一医院的餐桌号
    public function delRedisTableNum()
    {
        RedisService::set('zdOrderNum',0);
        RedisService::set('zyOrderNum',0);
    }

    /*
     * 每天上午08点与下午15点初始化库存
     */
    public function resetStock(){
        $sql = "select goods_id,restaurant_id,goods_sum,init_sum from gc_restaurant_goods where restaurant_id = 79 and cut_off = 0";

        $data = $res = $this->mysql->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
        foreach ($data as $key=>$value){
            $sql = "update gc_restaurant_goods set goods_sum = {$value['init_sum']} where goods_id = {$value['goods_id']}";
            $res = $this->mysql->exec($sql);
        }
    }

    /*
     * 每天13:30与19:30定时清理未取餐的菜品
     *
     */
    public function clearGoods(){
        $time = strtotime(date('Y-m-d',time()));
        $sqlOne = "update gc_restaurant_order_goods set goods_status = 2 where restaurant_id = 79 and pay_status = 1 and create_time > {$time}";
        $sqlTwo = "update gc_restaurant_order_goods_log set goods_status = 2 where restaurant_id = 79 and creation_time > {$time}";
        $resOne = $this->mysql->exec($sqlOne);
        $resTwo = $this->mysql->exec($sqlTwo);
        if(!($resOne&&$resTwo)){
            wlog(date("Y-m-d H:i:s")."data:clearGoods","zdxlh");
        }
    }

    public function doPrint(){
        for($i=1;$i<30;$i++){
            $this->toPrint();
            sleep(2);
        }
    }

    public function test(){
//        $redis = RedisQueueService::getInstance();
//        $data = $redis->pull('styy_print');
//        var_dump($data);
        var_dump(999);
    }

    
    /**
     *定时的在队列中获取打印信息
     */
     public function toPrint(){
        $redis = RedisQueueService::getInstance();
        $data = $redis->pull('styy_print');
        $data = json_decode($data,true);
        if(!$data){
            return true;
        }
        if($data['pay_type'] == 1){
                $payType = '微信';
        }
        if($data['pay_type'] == 2){
            $payType = '支付宝';
        }
        if($data['pay_type'] == 4){
            $payType = '一卡通';
        }
        if($data['pay_type'] == 5||6){
            $payType = '校园卡';
        }

        if(count($data['goods']['6'])>0){
            $service_port = 9100;
            $address = '192.168.1.111' ;
            $content = $this->content($data,$payType,$type='6');
            $this->Send_socket_connect($service_port,$address, $content,$type='hot_list',$data);
        }
        if(count($data['goods']['7'])>0){
            $service_port = 9100;
            $address = '192.168.1.111';
            $content = $this->content($data,$payType,$type='7');
            $this->Send_socket_connect($service_port,$address, $content,$type='cold_list',$data);
        }
        if(count($data['goods']['8'])>0){
            $service_port = 9100;
            $address = '192.168.1.111';
            $content = $this->content($data,$payType,$type='8');
            $this->Send_socket_connect($service_port,$address, $content,$type='water_list',$data);
        }
     }

     /*
      *拼接数据
      */
      private function content($data,$payType,$type){
            $htotal = 0;
            $hstr = '';
            foreach($data['goods'][$type] as $hk=>$hv){
                $hstr .= str_pad($hv['goods_name'],36,'　').' '. str_pad($hv['goods_num'],16,'　').'￥'.number_format($hv['goods_num']*$hv['goods_price'],2)  . "\x0D\x0A" . "\x0D\x0A";
                $htotal += $hv['goods_num']*$hv['goods_price'];
            }
            $content =
            "\x1B\x21\x08\x1B\x21\x10".'                 ' . $data['restaurant'] . "\x0A\x0A".
            '餐号：' . $data['order_num'] . "\x0A".' '."\x0A".
            "\x1B\x21\x00".'订单编号：' . $data['order_sn'] . "\x0A".' '."\x0A" .
            '打印时间:' .date("Y-m-d H:i:s"). "\x0A".' '."\x0A" .
            '支付方式:'. $payType . "\x0A".' '."\x0A" .
            '------------------------------------------------' . "\x0A".' '."\x0A" .
            "\x1B\x21\x08\x1B\x21\x10".str_pad('商品名称',36,'　').str_pad('数量',15).'小计'."\x0A".' '."\x0A" .$hstr ."\x0A".
            '------------------------------------------------' .
            "\x0A".'总计：' . $htotal .'元'.' '."\x0A".' '."\x0A"."\x1B\x21\x08\x1B\x21\x10".'              '.'青橄榄网络技术支持'.' '."\x0A".' '."\x0A".' '."\x0A".' '."\x0A".'  '."\x0A\x1D\x56\x01";
            /*$content =
            '================================' ."\x0D\x0A ".
            "\x1B\x21\x10".'餐厅名：' . $data['restaurant'] . "\x0D\x0A".
            '餐号：' . $data['order_num'] . "\x0D\x0A" .
            '订单编号：' . $data['order_sn'] . "\x0D\x0A" .
            '打印时间:'. date('Y-m-d H:i:s') . "\x0D\x0A" .
            '支付方式:'. $payType . "\x0D\x0A" .
            '------------------------' . "\x0D\x0A" .
            str_pad('商品名称',18,' ').str_pad('数量',12).'小计'."\x0D\x0A" .$hstr ."\x0D\x0A" .
            '------------------------' . "\x0D\x0A" .
            '总计：' . $htotal .'元'. "\x0D\x0A". "\x0D\x0A". "\x0D\x0A". "\x0D\x0A". "\x0D\x0A";
            str_pad('商品名称',24,' ').str_pad('数量',14).'小计'."\x0A".' '."\x0A" .$hstr ."\x0A".*/
            return $content;
      }
     
     /**
     *本地打印
     *
     */
     public function Send_socket_connect($service_port,$address, $in,$type,$data) {
    //创建 TCP/IP socket$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("could not create socket!");
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("could not create socket!");
        //设置超时时间
        $timeout = 2;
        $time = time();
        //设置非阻塞模式
        // @socket_set_nonblock($socket);
        /*$comand="\x1D\x56\x01\x48";
        $in=$in.$comand;*/

        $in = mb_convert_encoding($in, "GBK", "UTF-8");

        //超时判断
        while (!@socket_connect($socket, $address, $service_port)) {
            $err = socket_last_error($socket);
            // 连接成功，跳出循环
            if ($err === 10056) {
                break;
            }
            //连接失败，判断超时时间，停止
            if ((time() - $time) >= $timeout) {
                socket_close($socket);
                print('网络异常，请检查网络连接！！');
//                $redis = RedisQueueService::getInstance();
//                if($type =='hot_list'){
//                    $redis->push('zy_print',$data,$pushType='tail');
//                }
//                if($type =='cold_list'){
//                    //删除热菜后，再次入队列
//                    $data['hot_list'] = array();
//                    $redis->push('zy_print',$data,$pushType='tail');
//                }
//                if($type =='water_list'){
//
//                    //删除热冷菜，再次入队列
//                    $data['hot_list'] = array();
//                    $data['cold_list'] = array();
//                    $redis->push('zy_print',$data,$pushType='tail');
//                }
                exit();
            }
            // 刷新频率（250毫秒）
            usleep(250000);
        }
        //设置阻塞模式
        @socket_set_block($socket);
        //发送命令到设备
        socket_write($socket, $in, strlen($in));
        //关闭连接
        socket_close($socket);
    }


}
